package Dao;

import model.Interaction;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.DataSourceUtils;

import java.sql.SQLException;
import java.util.List;

public class InteractionDao {
    private QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());

    // 插入互动记录
    public boolean insertInteraction(Interaction interaction) {
        String sql = "INSERT INTO interaction (user_id, product_id, type, create_time) VALUES (?,?,?,?)";
        try {
            return r.update(sql, interaction.getUserId(), interaction.getProductId(), interaction.getType(), interaction.getCreateTime()) > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取某商品的互动记录（收藏/想要）数量，1=想要，2=收藏
    public int getInteractionCount( int productId, int type) {
        String sql = "SELECT COUNT(*) FROM interaction WHERE product_id = ? AND type = ?";
        try {
            Long count = r.query(sql, new ScalarHandler<Long>(), productId, type);
            return count != null ? count.intValue() : 0;
        } catch (SQLException e) {
            System.err.println("查询商品互动记录数量失败: " + e.getMessage());
            e.printStackTrace();
            return 0;
        }
    }

    // 获取所有互动记录
    public List<Interaction> getAllInteractions() {
        String sql = "SELECT * FROM interaction";
        try {
            return r.query(sql, new BeanListHandler<Interaction>(Interaction.class));
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}